package com.zlk.algorithm.huawei.leetcode.binaryTree;

import com.zlk.algorithm.util.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


/**
 * @program: algorithm
 * @ClassName Code22_inorderTraversal
 * @description: 二叉树的中序遍历
 * @author: slfang
 * @create: 2025-01-08 09:58
 * @Version 1.0
 **/
public class Code22_inorderTraversal {

    public List<Integer> inorderTraversal(TreeNode cur) {
        List<Integer> ans = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty()||cur!=null){
            if(cur!=null){
                stack.push(cur);
                cur = cur.left;
            }else{
                cur = stack.pop();
                ans.add(cur.val);
                cur = cur.right;
            }
        }
        return ans;
    }

    public List<Integer> inorderTraversalDg(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        setAns(root,ans);
        return ans;
    }

    private void setAns(TreeNode root, List<Integer> ans) {
        if(root==null){
            return ;
        }
        setAns(root.left,ans);
        ans.add(root.val);
        setAns(root.right,ans);
    }


}
